import { createRouter, createWebHistory } from 'vue-router'
import LoginForm from '../views/login/login.vue'
import CodeForm from '../views/login/codelogin.vue'
import CodeLoginForm from '../views/register/logincodevif.vue'
import RegisterForm from '../views/register/register.vue'
import CodeVerifyForm from '../views/register/regcode.vue'
import RetPwdForm from '../views/retpwd/retpwd.vue'
import RetPwdCodeForm from '../views/retpwd/retpwdvif.vue'
import Home from '../views/home/home.vue'
import spider from '../views/spider/spider.vue'
import good from '../views/good/good.vue'
import vsnack from '../views/echarts/vsnack.vue'
import vshoe from '../views/echarts/vshoe.vue'
import vphone from '../views/echarts/vphone.vue'
import vswear from '../views/echarts/vswear.vue'
import vcomputer from '../views/echarts/vcomputer.vue'
import goodsTotal from '../views/echarts/goodsTotal.vue'


const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', redirect:'/login' },
    { path: '/login', component: LoginForm },
    { path: '/codelogin', component: CodeForm },
    { path: '/codeloginverify', component: CodeLoginForm },
    { path: '/register', component: RegisterForm },
    { path: '/regcodeverify', component: CodeVerifyForm },
    { path: '/retpwd', component: RetPwdForm },
    { path: '/retpwdvif', component: RetPwdCodeForm },
    { 
      path: '/home',
      component: Home,
      meta: {
        requiresAuth: true,
      },
    },
    { path: '/spider', component: spider, meta: {
      requiresAuth: true,
    },},
    { path: '/vsnack', component: vsnack, meta: {
      requiresAuth: true,
    },},
    { path: '/vshoe', component: vshoe, meta: {
      requiresAuth: true,
    },},
    { path: '/vphone', component: vphone, meta: {
      requiresAuth: true,
    },},
    { path: '/vswear', component: vswear, meta: {
      requiresAuth: true,
    },},
    { path: '/vcomputer', component: vcomputer, meta: {
      requiresAuth: true,
    },},
    { path: '/total', component: goodsTotal, meta: {
      requiresAuth: true,
    },},
    { path: '/good', component: good, meta: {
      requiresAuth: true,
    },}
    // 你可以在这里添加更多的路由...
  ],
})
router.beforeEach((to, from, next) => {
  // 导航守卫中检查路由是否需要授权
  if (to.meta.requiresAuth) {
    // 在这里添加逻辑来获取 token 并设置请求头
    const token = localStorage.getItem('access_token');
    if (token) {
      // 如果有 token，则在请求头中添加 Authorization
      to.meta.headers = {
        'Authorization': `${token}`,
      };

      // 继续导航
      next();
    } else {
      // 如果没有 token，则重定向到登录页面
      next('/login');
    }
  } else {
    // 如果不需要授权，直接继续导航
    next();
  }
});
export default router
